import { useState, useEffect } from 'react';
import { Button, Col, Modal, Row, Spin, Image } from 'antd';
import * as moment from 'moment';
import { DownloadOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import { eventEmitter } from '..';
import type { PatrolRecordTableItem } from '../../types.d';

const PLATE_COLOR_MAP = new Map()
  .set(0, '-')
  .set(1, '蓝')
  .set(2, '黄')
  .set(3, '白')
  .set(4, '黑')
  .set(5, '绿');
interface DetailModalProps {
  visible: boolean;
  datasource: PatrolRecordTableItem[];
  data?: PatrolRecordTableItem;
  hasmore?: boolean;
  parentPage: number;
  parentPageSize: number;
  pageChange: (type: 'increase' | 'decrease') => void;
  setUnvisible: () => void;
}
export default (props: DetailModalProps) => {
  const {
    datasource,
    data,
    parentPage,
    visible,
    pageChange: parentPageChange,
    setUnvisible,
    // parentPageSize,
    hasmore,
  } = props;
  const getCurrentDetailData = (index: number) => {
    if (index < 0) return null;
    if (index > datasource.length - 1) return null;
    return datasource[index];
  };
  const [loading, setLoading] = useState<boolean>(false);
  const [detailDataIndex, setDetailDataIndex] = useState<number>(
    // eslint-disable-next-line no-underscore-dangle
    datasource.findIndex((v: PatrolRecordTableItem) => v._id === data?._id),
  );
  const [eventImageUrl, setEventImageUrl] = useState<string>(data?.eventImageUrl || '');
  const [composeImageUrl, setComposeImageUrl] = useState<string>('');
  const [currentData, setCurrentData] = useState<PatrolRecordTableItem | null>(null);
  useEffect(() => {
    const tempDetailData = getCurrentDetailData(detailDataIndex);
    if (tempDetailData) {
      setCurrentData(tempDetailData);
      setEventImageUrl(tempDetailData.eventImageUrl || '');
      setComposeImageUrl(tempDetailData.composeImageUrl || '');
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [detailDataIndex]);
  return (
    <Modal
      visible={visible}
      width="62vw"
      destroyOnClose
      maskClosable={false}
      bodyStyle={{ padding: '32px 40px 48px', minHeight: '60vh' }}
      footer={false}
      title={`设备编号: ${currentData?.deviceSn} 接收时间: ${
        currentData ? `${moment(currentData.createTime).format('YYYY-MM-DD HH:mm:ss')}` : ''
      }`}
      onCancel={() => setUnvisible()}
    >
      <div
        style={{
          position: 'absolute',
          left: '-80px',
          top: '30vh',
        }}
      >
        <Button
          size="large"
          style={{ border: 'none', background: 'none', height: 60 }}
          disabled={detailDataIndex <= 0 && parentPage <= 1}
          onClick={() => {
            if (detailDataIndex >= 1) {
              setDetailDataIndex(detailDataIndex - 1);
            } else if (parentPage > 1) {
              setLoading(true);
              parentPageChange('decrease');
              eventEmitter.once('patrol_record', (pageSize: number) => {
                setLoading(false);
                setDetailDataIndex(pageSize - 1);
              });
            }
          }}
        >
          <LeftOutlined style={{ fontSize: 52 }} />
        </Button>
      </div>
      <Spin tip="加载中..." spinning={loading}>
        <Row justify="space-around" gutter={8}>
          <Col span={4}>
            <div style={{ textAlign: 'center' }}>
              <strong>识别时间</strong>
              <div>
                {currentData && currentData.plateNumberRecognitionTime
                  ? `${moment(currentData.plateNumberRecognitionTime).format(
                      'YYYY-MM-DD HH:mm:ss',
                    )}`
                  : ''}
              </div>
            </div>
          </Col>
          <Col span={4}>
            <div style={{ textAlign: 'center' }}>
              <strong>泊位编号</strong>
              <div>{currentData?.parkingSpotId}</div>
            </div>
          </Col>
          <Col span={4}>
            <div style={{ textAlign: 'center' }}>
              <strong>车牌号码</strong>
              <div>{currentData?.plateNumber || '-'}</div>
            </div>
          </Col>
          <Col span={4}>
            <div style={{ textAlign: 'center' }}>
              <strong>车牌颜色</strong>
              <div>{currentData ? PLATE_COLOR_MAP.get(currentData.plateNumberColor) : '-'}</div>
            </div>
          </Col>
          <Col span={4}>
            <div style={{ textAlign: 'center' }}>
              <strong>车牌置信度</strong>
              <div>{currentData?.plateNumberConfidence || '-'}</div>
            </div>
          </Col>
        </Row>

        {composeImageUrl && (
          <div
            style={{
              background: 'black',
              border: '1px solid #FFF',
              padding: 2,
              marginTop: 10,
            }}
          >
            <Image
              alt="合成图片"
              // @ts-ignore
              style={{ width: '100%', height: '100%' }}
              src={composeImageUrl}
            />
          </div>
        )}

        {eventImageUrl && (
          <div
            style={{
              background: 'black',
              border: '1px solid #FFF',
              padding: 5,
              marginTop: 10,
            }}
          >
            <Image
              alt="事件图片"
              // @ts-ignore
              style={{ width: '100%', height: '100%' }}
              src={eventImageUrl}
            />
          </div>
        )}

        <div
          style={{ display: 'flex', marginTop: 10, alignItems: 'center', justifyContent: 'center' }}
        >
          {eventImageUrl && (
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              style={{ marginRight: 10, marginTop: 20 }}
              onClick={() => {
                if (eventImageUrl) {
                  window.open(
                    eventImageUrl.includes('https')
                      ? eventImageUrl
                      : eventImageUrl.replace('http://', 'https://'),
                  );
                }
              }}
            >
              下载事件图片
            </Button>
          )}

          {composeImageUrl && (
            <Button
              style={{ marginTop: 20 }}
              type="primary"
              icon={<DownloadOutlined />}
              onClick={() => {
                if (composeImageUrl) {
                  window.open(
                    composeImageUrl.includes('https')
                      ? composeImageUrl
                      : composeImageUrl.replace('http://', 'https://'),
                  );
                }
              }}
            >
              下载巡检图片
            </Button>
          )}
        </div>
      </Spin>

      <div
        style={{
          position: 'absolute',
          right: '-80px',
          top: '30vh',
        }}
      >
        <Button
          size="large"
          style={{ border: 'none', background: 'none', height: 60 }}
          disabled={detailDataIndex >= datasource.length - 1 && !hasmore}
          onClick={() => {
            if (detailDataIndex < datasource.length - 1) {
              setDetailDataIndex(detailDataIndex + 1);
            } else if (detailDataIndex >= datasource.length - 1) {
              setLoading(true);
              parentPageChange('increase');
              eventEmitter.once('patrol_record', () => {
                setLoading(false);
                setDetailDataIndex(0);
              });
            }
          }}
        >
          <RightOutlined style={{ fontSize: 52 }} />
        </Button>
      </div>
    </Modal>
  );
};
